package com.eascs.web.p2p.interceptor;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.p2p.common.entity.AdminUserEntity;
import com.eascs.site.cookie.CookieSpec;
import com.eascs.site.resolver.ExceptionHandler;
import com.eascs.web.sso.EaSsoService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

public class PermissionInterceptor extends HandlerInterceptorAdapter {
	private final Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);
	private final static String REQUEST_INIT_NAME = PermissionInterceptor.class.getName();
	public final static CookieSpec COOKIE_UUID = CookieSpec.build("u_id").httpOnly(false).maxAge(10 * 365 * 24 * 60 * 60);
	 private static final String[] IGNORE_URI = {"/admin/index", "/adminRest/login","/admin/captcha/yzm"};
	@Inject
	private ExceptionHandler exceptionHandler;
	@Inject
	EaSsoService eaSsoService;

	public PermissionInterceptor() {
		super();
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		 

	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	    boolean flag = false;
		String url = request.getRequestURL().toString();
        System.out.println(">>>: " + url);
        for (String s : IGNORE_URI) {
            if (url.contains(s)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
        	AdminUserEntity user = (AdminUserEntity) request.getSession().getAttribute("adminUser"); 
            if (user != null) {
            	flag = true;
            	}else{
            		
            		response.sendRedirect("/admin/index");
            	}
        }
        
        //设置菜单
        AdminUserEntity u = (AdminUserEntity) request.getSession().getAttribute("adminUser"); 
        if(u!=null){
             User user = eaSsoService.getUserByAccount(u.getAccount());
             UserHolder.setUser(user);
        }
       
        
		
	   return	flag;
    
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if (null != ex)
			this.exceptionHandler.handler(ex);
		super.afterCompletion(request, response, handler, ex);
	}

}
